package helper

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/base64"
	"io"
	"net"
	"strings"
)

const AuthKey string = "lxg1111111111111111111111111111111111"

func GetFirstMacAddress() (string, error) {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		return "", err
	}
	var macAddress = ""
	for _, netInterface := range netInterfaces {
		macAddr := netInterface.HardwareAddr.String()
		if len(macAddr) == 0 {
			continue
		}
		macAddress = strings.ReplaceAll(macAddr, ":", "")
		break
	}
	return strings.ToLower(macAddress), nil
}

func Padding(plainText []byte, blockSize int) []byte {
	padding := blockSize - len(plainText)%blockSize
	char := []byte{byte(padding)}
	newPlain := bytes.Repeat(char, padding)
	return append(plainText, newPlain...)
}

func UnPadding(plainText []byte) []byte {
	length := len(plainText)
	lastChar := plainText[length-1]
	padding := int(lastChar)
	return plainText[:length-padding]
}

func AESCbcEncrypt(secretKey, src string) string {
	key := []byte(secretKey)
	if len(key) > 16 {
		key = key[:16]
	}
	plaintext := []byte(src)
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	blockSize := block.BlockSize()
	plaintext = Padding(plaintext, blockSize)
	if len(plaintext)%aes.BlockSize != 0 {
		panic("plaintext is not a multiple of the block size")
	}
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
	return base64.StdEncoding.EncodeToString(ciphertext)
}

func AESCbcDecrypt(secretKey, src string) string {
	key := []byte(secretKey)
	if len(key) > 16 {
		key = key[:16]
	}
	ciphertext, _ := base64.StdEncoding.DecodeString(src)
	block, err := aes.NewCipher(key)
	if err != nil {
		return ""
	}
	if len(ciphertext) < aes.BlockSize {
		return ""
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]
	if len(ciphertext)%aes.BlockSize != 0 {
		return ""
	}
	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(ciphertext, ciphertext)
	ciphertext = UnPadding(ciphertext)
	return string(ciphertext)
}
